#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os, sys, copy, time, re, logging, urllib, urllib2
from parseFirst import *
from parseSecond import *

'''
抄袭了lazy bones的一些代码 以后改掉
'''
log=logging.getLogger("core")
'''

'''
def sizeread(size):
    '''传入整数,传出B/KB/MB'''
    #FIXME:这个有现成的函数没?
    if size>1024*1024:
        return '%0.2fMB' % (float(size)/1024/1024)
    elif size>1024:
        return '%0.2fKB' % (float(size)/1024)
    else:
        return '%dB' % size
class core:
    def __init__(self):
        self.songlist=[]  #这是已经确定要下载的音乐的list
        self.netlist=[]   #这是已经确定要下载的音乐的netlist
        self.song=[]  #总的音乐的list
        self.net=[]  #总的音乐的网址的list
        self.downloadnow=False
        try:
            os.mkdir('download')
        except:
            print u"已经存在"
            pass
        self.DIR='download/'
    def get_url_html(self,i=0):
        '''
        这是获得编号音乐的最终下载地址
        '''
        html=GetSong(self.songlist[i],self.net[i]).getHtml()
        return html
    def downone(self,i=0,callback=None):
        if os.path.exists(self.DIR+self.songlist[i]+".mp3"):
            print self.songlist[i],u'已经存在！'
            return
        url=self.get_url_html(i)
        if url:
            print u'正在下载:',self.songlist[i]
            if self.downloadnow and callback:
                callback(-1,self)
            try:
                self.download(url,self.DIR+self.songlist[i],callback=callback)
            except:
                print "there is something wrong!"
                return
        else:
            print u'出错了'
    def downall(self,callback=None):
        [self.downone(i, callback) for i in range((len(self.songlist)))]
    def download(self,remote_url,local_uri,callback=None):
        '''下载removete到local'''
        cache_uri=local_uri+'.downing'
        self.T=self.statT=time.time()
        (self.D,self.speed)=(0,0)
        c=callback if callback else self.update_progress
        if not self.downloadnow:
            c(-1,os.path.basename(local_uri),'')
        urllib.urlretrieve(remote_url, cache_uri, c)
        c(-2,os.path.basename(local_uri),'')
        speed=os.stat(cache_uri).st_size/(time.time()-self.statT)
        if callback==None:
            print speed
        os.rename(cache_uri, local_uri+'.mp3')
    def update_progress(self, blocks, block_size, total_size):
        '''默认的进度显示的回调函数'''
        if total_size > 0 and blocks >= 0:
            percentage = float(blocks) / (total_size/block_size+1) * 100
            if int(time.time()) != int(self.T):
                self.speed=(blocks*block_size-self.D)/(time.time()-self.T)
                (self.D,self.T)=(blocks*block_size,time.time())
            print '\r['+''.join(['=' for i in range((int)(percentage/2))])+'>'+ \
                ''.join([' ' for i in range((int)(50-percentage/2))])+ \
                (']  %0.2f%%  %s/s    ' % (percentage,sizeread(self.speed)))
    def get_songlist(self):
        return self.songlist
    def get_netlist(self):
        return self.netlist
    def append_list(self,song,net):
        self.songlist.append(song)
        self.netlist.append(net)
    def set_song_and_net(self,song,net):
        self.song=[]
        self.net=[]
        self.song=song
        self.net=net
Core=core()
        